package com.hrm.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.hrm.config.JSPPage;
import com.hrm.entity.Icon;
import com.hrm.entity.Message;
import com.hrm.service.IconService;
import com.hrm.util.JSONUtil;

@Controller
@RequestMapping("/icon.do")
public class IconAction {
	private static final Log log = LogFactory.getLog(IconAction.class);
	@Autowired
	private IconService iconService;


	public IconService getIconService() {
		return iconService;
	}

	public void setIconService(IconService iconService) {
		this.iconService = iconService;
	}

	@RequestMapping(params = "method=getIconById")
	public String getIconById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		long id = Long.parseLong(request.getParameter("id"));
		Icon icon = iconService.getIconById(id);
		if (icon != null) {
			String result = icon.toJSONString();
			try {
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!",
						new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}
	@RequestMapping(params = "method=getAllParentIcons")
	public String getAllParentIcons(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		List<Icon> icons = iconService.getAllParentIcons();
		if (icons != null) {
			String result = JSONUtil.parseList(icons);
			try {
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!",
						new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=getIcons")
	public String getIcons(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		List<Icon> icons = iconService.getIcons();
		if (icons != null) {
			String result = JSONUtil.parseList(icons);
			try {
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!",
						new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	@RequestMapping(params = "method=getIconsByParentId")
	public String getIconsByParentId(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		long id = Long.parseLong(request.getParameter("id"));
		List<Icon> icons = iconService.getIconsByParentId(id);
		if (icons != null) {
			String result = JSONUtil.parseList(icons);
			try {
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!",
						new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}



	@RequestMapping(params = "method=updateIcon")
	public String updateIcon(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
			long id = Long.parseLong(request.getParameter("id"));
			Icon icon = iconService.getIconById(id);
			if (icon == null) {
				Message message = new Message();
				message.setMsg("获取菜单信息失败!");
				message.setStatus("ERROR");
				message.setTimestamp(new Date());
				try {
					response.getWriter().print(message.toJSONString());
					return null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			log.error(icon);
			map.put("icon", icon);
			return JSPPage.ICON_EDIT;
	}


	@RequestMapping(params = "method=updateIconById")
	public String updateIconById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		long id = Long.parseLong(request.getParameter("id") == null ? "-1"
				: request.getParameter("id"));
		if (id == -1) {
			Message message = new Message();
			message.setMsg("必须传入图标ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("imgFile"); //获取上传文件
		String path = request.getParameter("path") == null ? ""
				: request.getParameter("path");
		if ("".equals(path) || path.getBytes().length >= 50) {
			Message message = new Message();
			message.setMsg("图标路径不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String tmp = this.getClass().getResource("/").getPath();
		 String imagePath=tmp.substring(0,tmp.indexOf("WEB-INF"))+"images/icons/"+path;
		 path="images/icons/"+path;
		 if(multipartFile!=null&&multipartFile.getSize()>0){
			 File file = new File(imagePath); //新建一个文件
			   try {
				  multipartFile.getFileItem().write(file); //将上传的文件写入新建的文件中
			   } catch (Exception e) {
				   	Message message = new Message();
					message.setMsg("图标文件替换失败!");
					message.setStatus("ERROR");
					message.setTimestamp(new Date());
					try {
						response.getWriter().print(message.toJSONString());
						return null;
					} catch (IOException e1) {
						e1.printStackTrace();
					}
			    e.printStackTrace();
			   }
			 
		 }
		 
		String title = request.getParameter("title") == null ? ""
				: request.getParameter("title");
		
		if ("".equals(title) || title.getBytes().length >= 50) {
			Message message = new Message();
			message.setMsg("图标标签不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		int parentId = request.getParameter("icon") == null ? -1
				: Integer.parseInt(request.getParameter("icon"));
		String level = request.getParameter("level") == null ? "-1"
				: request.getParameter("level");
		log.error("level==============="+level);
		Icon icon = new Icon();
		icon.setId((int) id);
		icon.setPath(path);
		icon.setTitle(title);
		if("-1".equals(level)){
			 icon.setParentId(-1);
		}else if("1".equals(level)){
			 icon.setParentId(parentId);
		}
		Message message = new Message();
		if (iconService.updateIcon(icon) < 1) {
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			message.setMsg("编辑图标成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

	@RequestMapping(params = "method=deleteIconById")
	public String deleteIconById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		long id = Long.parseLong(request.getParameter("id") == null ? "-1"
				: request.getParameter("id"));
		if (id == -1) {
			Message message = new Message();
			message.setMsg("必须传入图标ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Message message = new Message();
		if (iconService.deleteIconById(id) < 1) {
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			message.setMsg("删除图标成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}
	@RequestMapping(params = "method=deleteIconsByParentId")
	public String deleteIconsByParentId(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		long id = Long.parseLong(request.getParameter("id") == null ? "-1"
				: request.getParameter("id"));
		if (id == -1) {
			Message message = new Message();
			message.setMsg("必须传入图标ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Message message = new Message();
		if (iconService.deleteIconsByParentId(id) < 1) {
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			message.setMsg("删除图标成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}


	@RequestMapping(params = "method=addIcon")
	public String addIcon(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		 CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("imgFile"); //获取上传文件
		 int parentId = request.getParameter("parentId") == null ? -1
				: Integer.parseInt(request.getParameter("parentId"));
		 String path = request.getParameter("path") == null ? ""
				: request.getParameter("path");
		 String title = request.getParameter("title") == null ? ""
				: request.getParameter("title");
		 String tmp = this.getClass().getResource("/").getPath();
		 String imagePath=tmp.substring(0,tmp.indexOf("WEB-INF"))+"images/icons/"+path;
		 path="images/icons/"+path;
		 File file = new File(imagePath); //新建一个文件
		   try {
			  multipartFile.getFileItem().write(file); //将上传的文件写入新建的文件中
		   } catch (Exception e) {
			   	Message message = new Message();
				message.setMsg("图标文件上传失败!");
				message.setStatus("ERROR");
				message.setTimestamp(new Date());
				try {
					response.getWriter().print(message.toJSONString());
					return null;
				} catch (IOException e1) {
					e1.printStackTrace();
				}
		    e.printStackTrace();
		   }
		if ("".equals(path) || path.getBytes().length >= 50) {
			Message message = new Message();
			message.setMsg("图标路径不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Icon icon = new Icon();
		icon.setParentId(parentId);
		icon.setPath(path);
		icon.setTitle(title);
		String level=request.getParameter("level");
		int id=request.getParameter("icon")==null?-1:Integer.parseInt(request.getParameter("icon"));
		if("-1".equals(level)){
			 icon.setParentId(-1);
		}else if("1".equals(level)){
			 icon.setParentId(id);
		}
		Message message = new Message();
		if (iconService.addIcon(icon) < 1) {
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			message.setMsg("新增图标成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

}
